import {
	store,
	mutations
} from '@/uni_modules/uni-id-pages/common/store.js'

import { usePinia, useNotificationStore } from '@/stores/index.js'

export async function connectWebSocket() {
	usePinia()
	const notificationStore = useNotificationStore()
	if(!store.hasLogin){
		// console.log('未登录');
		return
	}
	// 快速建立websocket连接
	const exampleWebSocket = await uniCloud.connectWebSocket({
		name: "wallpaper-connectWebSocket",
		query: {
			user_id: store.userInfo._id
		}
	})
	// 连接成功时触发
	exampleWebSocket.onOpen(event => {
		// console.log("WebSocket:open", event)
		notificationStore.getNotification()
	})
	// 收到数据时触发
	exampleWebSocket.onMessage(event => {
		// console.log("WebSocket:message", event.data)
		// 字符串转json
		let data = JSON.parse(event.data)
		// 首次建立连接时，收到返回的connectionId存到缓存
		if (data.type == 'connectionId') {
			uni.setStorageSync('connectionId', data.connectionId)
		}else if (data.type == 'notification') {
			// 收到通知 重新获取通知列表,触发更新tabbar角标, 
			// 更新全局状态同时响应式更新通知图标角标
			notificationStore.getNotification()
		}
	})
	// 连接被关闭时触发
	exampleWebSocket.onClose(event => {
		// console.log("WebSocket:close", event)
		// 删除connectionId
		uni.removeStorageSync('connectionId')
	})
	// 连接因错误而关闭时触发
	exampleWebSocket.onError(event => {
		// console.log("WebSocket:error", event)
		// 删除connectionId
		uni.removeStorageSync('connectionId')
		
	})
}